<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Download, ArrowDown } from '@element-plus/icons-vue'
import { page,save as bedSave,bedcount } from '@/api/bed'
import { save as elderSave } from '@/api/elderInfo'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'

const router = useRouter();
// 状态映射
const statusMap = {
  0: '空闲',
  1: '占用',
  2: '维修',
  3: '禁用'
}
const statusTagType = {
  0: 'success',
  1: 'warning',
  2: 'danger',
  3: 'info'
}
const handleAdd = () => {
  router.push('/bedManagement/add'); // 跳转到新增床位页面
};
// 数据加载
const loading = ref(false)
const tableData = ref([])
const countInfo =reactive({
  bedOccupy:0,
  bedNotOccupy:0,
  wardNumber:0
})
const searchForm = reactive({
  status: null,
  wardId: null
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()
const form = reactive({
  bedId: null,
  bedNumber: '',
  status: null,
  floor: 1,
  price: 0,
  wardId: null
})
// 编辑对话框相关
const editDialogVisible = ref(false)
const currentBed = ref(null)
const formElder = reactive({
  elderlyId: null
})
const rules = {
  bed_number: [{ required: true, message: '请输入床位编号', trigger: 'blur' }],
  floor: [{ required: true, message: '请选择楼层', trigger: 'change' }]
}
const elderlyList = ref([]) // 老人列表
// 方法
const fetchData = async () => {
  try {
    loading.value = true
    // 构建查询参数，过滤掉空值
    const params = {
      ...Object.fromEntries(
        Object.entries(searchForm).filter(([_, v]) => v !== null && v !== '')
      ),
      pageNo: pagination.current,
      pageSize: pagination.size
    }
    const countInfoRes = await bedcount()
    countInfo.bedNotOccupy=countInfoRes.data.bedNotOccupy
    countInfo.bedOccupy=countInfoRes.data.bedOccupy
    countInfo.wardNumber=countInfoRes.data.wardNumber
    
    const res = await page(params)
    tableData.value = res.data.records
    console.log(tableData.value)
    pagination.total = res.data.total
    elderlyList.value=tableData.value[0].elderMap
    console.log(elderlyList)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const resetSearch = () => {
  searchForm.status = null
  searchForm.wardId = null
  handleSearch()
}
const currentElder=ref([])
// 编辑床位
const handleEdit = (row) => {
  currentBed.value = row
  formElder.elderlyId = row.elderlyId || null
  console.log(formElder.elderlyId)
  editDialogVisible.value = true
  currentElder.value=row.elderly
}
const quiteBed=async (row)=>{
  currentBed.value = row
    try {
  console.log("ok2")
      // 取消分配 - 更新床位信息
      await bedSave({
        bedId: currentBed.value.bedId,
        bedNumber: currentBed.value.bedNumber,
        elderlyId:null,
        status: 0, // 设置为空闲状态
        floor: currentBed.value.floor,
        price: currentBed.value.price,
        wardId: currentBed.value.wardId
      });
      
      ElMessage.success('取消分配成功');
          editDialogVisible.value = false;
    await fetchData(); // 刷新表格数据
    }catch (error) {
    console.error('操作失败:', error);
    ElMessage.error(error.message || '操作失败');
  }
}
// 分配老人
const assignBed = async (elderlyId) => {
  try {
      console.log("ok1")
      // 分配老人到床位 - 更新床位信息
      if(elderlyId){
        await bedSave({
        bedId: currentBed.value.bedId,
        bedNumber: currentBed.value.bedNumber,
        elderlyId: elderlyId,
        status: 1, // 设置为占用状态
        floor: currentBed.value.floor,
        price: currentBed.value.price,
        wardId: currentBed.value.wardId
      })
      ElMessage.success('修改成功');
    editDialogVisible.value = false;
      }else{
        await bedSave({
        bedId: currentBed.value.bedId,
        bedNumber: currentBed.value.bedNumber,
        elderlyId: elderlyId,
        floor: currentBed.value.floor,
        price: currentBed.value.price,
        wardId: currentBed.value.wardId
      })
      ElMessage.success('修改成功');
    editDialogVisible.value = false;
      }
      
    await fetchData(); // 刷新表格数据
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error(error.message || '操作失败');
  }
}
// 初始化
onMounted(() => {
  fetchData()
  // 这里应该添加获取病房列表的API调用
  // getWardList().then(res => wardList.value = res.data)
})
</script>

<template>
<div id="app">
    <div class="bed-management">
      <!-- 顶部标题区域 -->
      <div class="header">
        <div>
          <h1 class="header-title">
            <i class="fas fa-bed"></i>
            床位管理系统
          </h1>
        </div>
        <div class="actions">
          <el-button type="primary" class="action-button" @click="handleAdd">
            <i class="fas fa-plus"></i> 新增床位
          </el-button>
        </div>
      </div>
      
      <!-- 统计卡片 -->
      <div class="stats-card">
        <div class="stat-item">
          <div class="stat-icon beds">
            <i class="fas fa-bed"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ pagination.total }}</div>
            <div class="stat-label">总床位</div>
          </div>
        </div>
        
        <div class="stat-item">
          <div class="stat-icon occupied">
            <i class="fas fa-user-injured"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ countInfo.bedOccupy }}</div>
            <div class="stat-label">已占用</div>
          </div>
        </div>
        
        <div class="stat-item">
          <div class="stat-icon free">
            <i class="fas fa-bed-empty"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{countInfo.bedNotOccupy }}</div>
            <div class="stat-label">空闲中</div>
          </div>
        </div>
        
        <div class="stat-item">
          <div class="stat-icon rooms">
            <i class="fas fa-door-open"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ countInfo.wardNumber }}</div>
            <div class="stat-label">房间数</div>
          </div>
        </div>
      </div>
      
      <!-- 搜索卡片 -->
      <div class="search-card">
        <div class="search-container">
          <el-form :model="searchForm" class="search-form">
            <el-form-item label="房间号">
              <el-input 
                v-model="searchForm.wardId" 
                placeholder="输入房间号" 
                clearable
                :prefix-icon="Search"
              />
            </el-form-item>
            
            <el-form-item label="状态">
              <el-select 
                v-model="searchForm.status" 
                placeholder="全部状态" 
                clearable
              >
                <el-option label="空闲" :value="0"/>
                <el-option label="占用" :value="1"/>
                <el-option label="维修" :value="2"/>
                <el-option label="禁用" :value="3"/>
              </el-select>
            </el-form-item>
            
            <el-button type="primary" @click="handleSearch">
              <i class="fas fa-search"></i> 搜索
            </el-button>
            
            <el-button @click="resetSearch">
              <i class="fas fa-sync-alt"></i> 重置
            </el-button>
          </el-form>
        </div>
      </div>
      
      <!-- 数据卡片 -->
      <div class="data-card">
        <el-table 
          :data="tableData" 
          v-loading="loading"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column label="楼层" prop="floor" width="100" align="center">
            <template #default="{row}">
              <el-tag type="info">{{ row.floor }}层</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="房间号" prop="wardId" width="150" align="center">
            <template #default="{row}">
              <span style="font-weight: 600;">{{ row.wardId }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="bedNumber" label="床位编号" width="150" align="center"/>
          
          <el-table-column label="状态" width="120" align="center">
            <template #default="{row}">
              <el-tag :type="statusTagType[row.status]" class="status-tag">
                {{ statusMap[row.status] }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="居住老人" show-overflow-tooltip>
            <template #default="{row}">
              <div v-if="row.elderly">
                <i class="fas fa-user"></i> {{ row.elderly.name }}
              </div>
              <div v-else class="elderly-empty">
                <i class="fas fa-user-slash"></i> 无居住老人
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="价格(元/天)" prop="price" width="150" align="right">
            <template #default="{row}">
              <span style="color: #e74c3c; font-weight: 600;">¥{{ row.price }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="250" fixed="right" align="center">
            <template #default="{row}">
              <el-button size="small" @click="handleEdit(row)">
                <i class="fas fa-edit"></i> 编辑
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="quiteBed(row)"
                v-if="row.status === 1"
              >
                <i class="fas fa-user-times"></i> 取消分配
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="fetchData"
            @current-change="fetchData"
          />
        </div>
      </div>
      
      <!-- 编辑对话框 -->
      <el-dialog 
        v-model="editDialogVisible" 
        class="edit-dialog"
        width="600px"
      >
        <div class="dialog-header">
          <i class="fas fa-bed"></i>
          <h2>编辑床位 - {{ currentBed?.bedNumber }}</h2>
        </div>
        
        <div class="dialog-content">
          <el-form :model="form" label-width="120px">
            <el-form-item label="床位状态">
              <el-tag :type="statusTagType[currentBed?.status]" class="status-tag" size="large">
                {{ statusMap[currentBed?.status] }}
              </el-tag>
            </el-form-item>
            
            <el-form-item label="价格(元/天)" style="display: flex; align-items: center">
              <el-input-number 
                v-model="currentBed.price" 
                :min="0" 
                :step="100"
                controls-position="right"
                style="width: 200px;"
              />
            </el-form-item>
            
            <el-form-item label="分配老人" v-if="currentBed?.status === 0">
              <el-select 
                v-model="formElder.elderlyId" 
                placeholder="请选择老人"
                filterable
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="elderly in elderlyList"
                  :key="elderly.elderlyId"
                  :label="`${elderly.value}`"
                  :value="elderly.elderlyId"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="当前老人" v-if="currentBed?.status === 1">
              <div style="font-weight: 500;">
                <i class="fas fa-user"></i> {{ currentBed?.elderly?.name || '无' }}
              </div>
            </el-form-item>
          </el-form>
        </div>
        
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="assignBed(formElder.elderlyId)">
            保存
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
    }
    
    body {
      background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
      min-height: 100vh;
      padding: 20px;
    }
    
    .bed-management {
      max-width: 1400px;
      margin: 0 auto;
    }
    
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25px;
      padding: 20px;
      background: white;
      border-radius: 16px;
      box-shadow: 0 6px 20px rgba(0, 0, 150, 0.08);
    }
    
    .header-title {
      font-size: 28px;
      font-weight: 600;
      color: #2c3e50;
      display: flex;
      align-items: center;
      gap: 12px;
    }
    
    .header-title i {
      color: #409EFF;
      font-size: 32px;
    }
    
    .stats-card {
      display: flex;
      gap: 20px;
      margin-bottom: 30px;
      flex-wrap: wrap;
    }
    
    .stat-item {
      flex: 1;
      min-width: 200px;
      background: white;
      border-radius: 16px;
      padding: 25px;
      box-shadow: 0 4px 12px rgba(0, 0, 150, 0.05);
      transition: transform 0.3s ease, box-shadow 0.3s ease;
      display: flex;
      align-items: center;
      gap: 15px;
    }
    
    .stat-item:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 20px rgba(0, 0, 150, 0.1);
    }
    
    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28px;
      color: white;
    }
    
    .stat-icon.beds {
      background: linear-gradient(135deg, #3498db, #64b5ff);
    }
    
    .stat-icon.occupied {
      background: linear-gradient(135deg, #e74c3c, #ff7979);
    }
    
    .stat-icon.free {
      background: linear-gradient(135deg, #2ecc71, #64d8a8);
    }
    
    .stat-icon.rooms {
      background: linear-gradient(135deg, #9b59b6, #c8a2e0);
    }
    
    .stat-content {
      flex: 1;
    }
    
    .stat-number {
      font-size: 28px;
      font-weight: 700;
      color: #2c3e50;
    }
    
    .stat-label {
      font-size: 16px;
      color: #7f8c8d;
      margin-top: 5px;
    }
    
    .search-card {
      background: white;
      border-radius: 16px;
      padding: 25px;
      box-shadow: 0 6px 20px rgba(0, 0, 150, 0.08);
      margin-bottom: 30px;
    }
    
    .search-container {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
    }
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      flex: 1;
    }
    
    .search-form .el-input, 
    .search-form .el-select {
      width: 200px;
    }
    
    .actions {
      display: flex;
      gap: 15px;
      flex-shrink: 0;
    }
    
    .action-button {
      display: flex;
      align-items: center;
      gap: 8px;
      height: 40px;
    }
    
    .data-card {
      background: white;
      border-radius: 16px;
      padding: 30px;
      box-shadow: 0 6px 20px rgba(0, 0, 150, 0.08);
      margin-bottom: 30px;
    }
    
    .el-table {
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 4px 12px rgba(0, 0, 150, 0.05);
      border: 1px solid #ebeef5;
    }
    
    .el-table :deep(.el-table__header) th {
      background-color: #f5f9ff;
      color: #409EFF;
      font-weight: 600;
    }
    
    .el-table :deep(.el-table__row) {
      transition: background-color 0.2s ease;
    }
    
    .el-table :deep(.el-table__row:hover) {
      background-color: #f8fafc !important;
    }
    
    .el-table :deep(.el-table__cell) {
      padding: 12px 0;
    }
    
    .status-tag {
      font-weight: 500;
      border-radius: 12px;
      padding: 6px 12px;
    }
    
    .pagination-container {
      display: flex;
      justify-content: flex-end;
      margin-top: 30px;
    }
    
    .edit-dialog {
      border-radius: 16px;
      overflow: hidden;
    }
    
    .dialog-header {
      background: linear-gradient(90deg, #409EFF, #64b5ff);
      color: white;
      padding: 20px;
      display: flex;
      align-items: center;
      gap: 12px;
    }
    
    .dialog-header i {
      font-size: 24px;
    }
    
    .dialog-content {
      padding: 25px;
    }
    
    .dialog-footer {
      padding: 20px;
      text-align: right;
      border-top: 1px solid #eee;
    }
    
    .el-button--danger {
      background: linear-gradient(90deg, #e74c3c, #ff7979);
      border: none;
    }
    
    .el-button--danger:hover {
      background: linear-gradient(90deg, #ff7979, #e74c3c);
    }
    
    @media (max-width: 992px) {
      .search-container {
        flex-direction: column;
      }
      
      .search-form {
        width: 100%;
      }
      
      .actions {
        width: 100%;
        justify-content: flex-end;
      }
      
      .stat-item {
        min-width: calc(50% - 20px);
      }
    }
    
    @media (max-width: 768px) {
      .header {
        flex-direction: column;
        align-items: flex-start;
        gap: 20px;
      }
      
      .stat-item {
        min-width: 100%;
      }
      
      .search-form .el-input, 
      .search-form .el-select {
        width: 100%;
      }
    }
  </style>